/*
 *  Copyright 2001-2004 The Apache Software Foundation
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package ar.uba.fi.posgrado.academy.service.impl;

import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import ar.uba.fi.posgrado.academy.dao.SubjectDAO;
import ar.uba.fi.posgrado.academy.model.Subject;
import ar.uba.fi.posgrado.academy.service.SubjectService;
import ar.uba.fi.posgrado.common.dao.DAOException;
import ar.uba.fi.posgrado.common.dao.NoSuchEntityException;
import ar.uba.fi.posgrado.common.exception.MissingArgumentException;
import ar.uba.fi.posgrado.common.exception.PosgradoException;
import ar.uba.fi.posgrado.common.exception.PosgradoRuntimeException;
import ar.uba.fi.posgrado.common.exception.RepeatedNameException;
import ar.uba.fi.posgrado.common.model.User;

public class SubjectServiceImpl implements SubjectService {

	private static Logger logger = Logger.getLogger(SubjectServiceImpl.class);

	private SubjectDAO subjectDAO;

	public SubjectDAO getSubjectDAO() {
		return subjectDAO;
	}

	public void setSubjectDAO(SubjectDAO subjectDAO) {
		this.subjectDAO = subjectDAO;
	}

	@Transactional(readOnly = false, propagation = Propagation.REQUIRED)
	public void create(Subject subject) throws MissingArgumentException,
			PosgradoException {

		if (StringUtils.isBlank(subject.getCode())
				|| StringUtils.isBlank(subject.getName())
				|| StringUtils.isBlank(subject.getCurriculum())) {
			String mensaje = "El codigo, el nombre y la curricula son datos obligatorios para guardar una materia";
			throw new MissingArgumentException(mensaje);
		}

		if (subject.getCredits() < 0) {
			throw new MissingArgumentException(
					"Los creditos de una materia deben ser mayores que cero");
		}

		try {
			this.getSubjectDAO().save(subject); 
			logger.info("Materia: " + subject + " creada con exito");
		} catch (DAOException e) {
			throw new PosgradoException("Excepcion al crear la materia: "
					+ subject, e);
		}
	}

	@Transactional(readOnly = false, propagation = Propagation.REQUIRED)
	public void delete(Subject t) throws PosgradoRuntimeException,
			PosgradoException {
		this.getSubjectDAO().remove(t);
	}

    @Transactional(readOnly = true)
	public List<Subject> getAll() throws PosgradoRuntimeException,
			PosgradoException {
		return this.getSubjectDAO().findAll();
	}

    @Transactional(readOnly = true)
	public Subject getById(Long id) throws PosgradoRuntimeException,
			PosgradoException {
		return (Subject) this.getSubjectDAO().findById(id);
	}

	@Transactional(readOnly = false, propagation = Propagation.REQUIRED)
	public Subject update(Subject subject) throws PosgradoRuntimeException,
			PosgradoException {
		Subject toUpdateSubject = this.getById(subject.getId());

		if (StringUtils.isBlank(subject.getCode())
				|| StringUtils.isBlank(subject.getName())
				|| StringUtils.isBlank(subject.getCurriculum())) {
			String mensaje = "El codigo, el nombre y la curricula son datos obligatorios para guardar una materia";
			throw new MissingArgumentException(mensaje);
		}

		if (!subject.getId().equals(toUpdateSubject.getId())) {
			try {
				Subject s = this.getById(subject.getId());
				if (s.getId() != toUpdateSubject.getId()) {
					throw new RepeatedNameException(
							"No se puede actualizar la materia. Ya hay otra materia en el sistema con el id "
									+ subject.getId());
				}
			} catch (NoSuchEntityException e) {
				// significa que esta todo bien y puede actualizar la materia
				toUpdateSubject.setName(subject.getName());
				toUpdateSubject.setCode(subject.getCode());
				toUpdateSubject.setCredits(subject.getCredits());
				toUpdateSubject.setCurriculum(subject.getCurriculum());

				this.getSubjectDAO().update(toUpdateSubject);
				subject = toUpdateSubject;
			}
		} else {
			toUpdateSubject.setName(subject.getName());
			toUpdateSubject.setCode(subject.getCode());
			toUpdateSubject.setCredits(subject.getCredits());
			toUpdateSubject.setCurriculum(subject.getCurriculum());

			this.getSubjectDAO().update(toUpdateSubject);
			subject = toUpdateSubject;
		}
		return subject;
	}

	public List<Subject> getAllValid() throws PosgradoRuntimeException, PosgradoException {
		return this.getSubjectDAO().findAllValid();
	}

	/** 
	 * @see ar.uba.fi.posgrado.common.service.GenericService#filter(java.util.List, ar.uba.fi.posgrado.common.model.User)
	 */
	public List<Subject> filter(List<Subject> list, User user)
			throws PosgradoRuntimeException, PosgradoException {
		return list;
	}
	
	
}
